import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// 设置基本地址
const service = axios.create({
  baseURL: 'http://localhost:8081',
  timeout: 5000
})

// request interceptor
service.interceptors.request.use(
  // 设置请求头
  config => {
    if (store.getters.token) {
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// 应答拦截器
service.interceptors.response.use(

  response => {
    const res = response.data
    console.info(res.head)

    // 如果返回的状态码为-1,请求失败
    if (res.head.code !== '0') {
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res.body
    }
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 100000000
    })
    return Promise.reject(error)
  }
)

export default service
